<template>
  <div class="page_companyHome">
    <van-nav-bar title="我的公司首页" left-arrow @click-left="backMinePage">
      <template #right>
        <van-icon
          @click="
            searchType = !searchType
            onClearVal(!!searchParams.keyword)
          "
          name="search"
          size="20"
          style="margin-right: 20px; "
        />
        <van-icon name="ellipsis" size="18" @click="showOverlay = true" />
      </template>
    </van-nav-bar>
    <van-search
      v-if="searchType"
      v-model="searchParams.keyword"
      placeholder="请输入搜索关键词"
      show-action
      shape="round"
      @search="onSearch"
      @clear="onClearVal"
    >
      <div slot="action" @click="onSearch">搜索</div>
    </van-search>
    <van-overlay :show="showOverlay" @click="showOverlay = false" class-name="over_layer">
      <van-cell-group class="layer">
        <van-cell value="公司公告" @click="$router.push('/myCompany/Notice')" />
        <van-cell value="我的发布" @click="$router.push('/myCompany/MyPublish')" />
        <van-cell :value="`${myCompanyDetailInfo.follow || 0}个粉丝`" />
        <!--        <van-cell value="公司二维码" @click="$router.push({
              name: 'guide',
              query: {
                source_type: 'V',
              },
            })" />
        <van-cell value="公司链接" @click="showDig" />-->
        <van-badge :content="reportCount > 0 ? reportCount : ''" max="99">
          <van-cell value="收到的举报" @click="toComplaintList('收到的举报', reportCount)" />
        </van-badge>
        <!-- 第一版屏蔽 -->
        <template v-if="false">
          <van-badge :content="suggestCount > 0 ? suggestCount : ''" max="99">
            <van-cell value="收到的投诉建议" @click="toComplaintList('收到的投诉建议', suggestCount)" />
          </van-badge>
        </template>
        <van-cell value="公司介绍" @click="$router.push('/myCompany/Introduce')" />
        <van-cell value="我发出去的收集表" @click="$router.push('/myCompany/jobSheet')" />
        <van-cell
          value="设置线下报名渠道来源"
          @click="
            $router.push({
              path: '/myCompany/channel',
              query: {
                companyId
              }
            })
          "
        />
      </van-cell-group>
    </van-overlay>
    <!-- 轮播图 -->
    <van-swipe
      :autoplay="3000"
      class="my-swipe"
      indicator-color="white"
      ref="mySwipe"
      :stop-propagation="false"
      @change="onImageChange"
    >
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <van-image lazy-load :src="image" style="width: 100%;" @click="bigImage(images)" />
      </van-swipe-item>
    </van-swipe>
    <!-- 公司公告 -->
    <div class="company-notice" @click="toNotice">
      <div class="notice-wrap">
        <div class="notice-left">公司公告：</div>
        <div class="notice-right">
          <van-notice-bar left-icon="volume-o" :scrollable="false">
            <van-swipe vertical class="notice-swipe" :autoplay="3000" :show-indicators="false">
              <van-swipe-item v-for="(item, index) in noticeList" :key="index">{{ item }}</van-swipe-item>
            </van-swipe>
          </van-notice-bar>
        </div>
      </div>
    </div>

    <!-- 筛选条 -->
    <com-filter-bar
      @clickFilter="clickFilter_myCompany"
      @getFilterBarVal="getFilterBarVal_myCompany"
      :isDoFilter="isDoFilterAction"
    ></com-filter-bar>

    <com-filter-popup
      ref="comFilterPopupRef_myCompany"
      @getFilterPopUpVal="toGetFilterPopUpVal_myCompany"
    ></com-filter-popup>

    <!-- 卡片 -->
    <div class="jobArr" v-if="ownerJobList.length">
      <job-item-for-recruit
        v-show="item.job_category_id == selectId || selectType"
        v-for="(item, indexs) in ownerJobList"
        :key="item.id"
        :jobItem="item"
        :serchType="1"
        :keyWord="'companyHome'"
        @changeJobStatus="toChangeJobStatus"
      ></job-item-for-recruit>
      <van-pagination
        v-show="total > 0"
        style="margin: 10px 0"
        v-model="searchParams.pageIndex"
        :total-items="total"
        @change="handlePaginationChange_myCompany"
      >
        <template #prev-text>
          <van-icon name="arrow-left" />
        </template>
        <template #next-text>
          <van-icon name="arrow" />
        </template>
        <template #page="{ text }">{{ text }}</template>
      </van-pagination>
    </div>

    <van-divider style="margin-top: 100px" v-else>无记录</van-divider>
  </div>
</template>

<script>
import Vue from 'vue'
import {ImagePreview, Toast, Dialog} from 'vant'
import comJobItem from '../../../components/comJobItem'
import jobItemForRecruit from '../recruitmentManagement/common/jobItemForRecruit'

import comFilterBar from '../../../components/comFilterBar'
import comFilterPopup from '../../../components/comFilterPopup'

import banner_1 from '@/assets/img/home/banner_1.jpg'
import banner_2 from '@/assets/img/home/banner_2.jpg'
import banner_3 from '@/assets/img/home/banner_3.jpg'
import {obj, recruitStatusObj} from '../../../constants/comUtils'
import {jobTypeList} from '../../../constants/comUtils'
import {reqHomeCompanyLists, searchKeywords, screenCompanyLists, reqChangeJobStatus} from '../../../api/myCompany.js'

import {mapGetters} from 'vuex'
import {concatIds} from '../../../utils'
import {base_url} from '../../../constants/comUtils'
import {mixin_one} from '../../../mixin/mixin'

export default {
  name: 'companyHome',
  components: {
    jobItemForRecruit,
    comFilterBar,
    comFilterPopup
  },
  mixins: [mixin_one],
  data() {
    return {
      base_url,
      images: [banner_1, banner_2, banner_3],
      showOverlay: false,
      ownerJobList: [],
      jobTypeList,
      // 检索参数
      searchParams: {
        keyword: '', // 搜索关键字
        jobcategory: '', // 招聘类型(全职、兼职、小时工)
        minSalary: null, // 起始薪资
        maxSalary: null, // 最大薪资
        adrtype: '', // 按地址
        classproperties: '', // 班制属性
        jobattributes: '', // 职位属性
        benefits: '', // 福利列表
        paymode: '', // 算薪方式
        payday: '', // 发薪日
        payMoneyDetailDate: '', // 发薪日详细日期
        createTime: '', // 发布时间
        pageIndex: 1, // 当前页
        pageSize: 10, // 每页显示条数
        status: '1'
      },
      total: 0,
      selectId: '',
      selectType: true,
      searchType: false,
      companyId: '',
      user_id: '',
      noticeList: [],
      loadType: false,
      // 收到的举报条数数
      reportCount: 0,
      // 收到的投诉条数
      suggestCount: 0,
      myCompanyDetailInfo: {}
    }
  },
  computed: {
    ...mapGetters(['allUserInfo'])
  },
  async created() {
    // 初始参数
    await this._initPageData_myCompany()
    this.getNotice()

    // 获取举报未读消息
    this.getReportNotice()
  },
  async mounted() {
    //   message: '加载中...',
    //   forbidClick: true, // 禁止背景点击
    //   duration: 0 // 持续展示
    // })
  },
  methods: {
    // 待完善
    async _initPageData_myCompany() {
      const comMesRes = await this.$api.myCompany.reqGetCompanyMes()

      this.companyId = comMesRes.data.id
      this.user_id = comMesRes.data.apply_userid

      if (comMesRes.code === 200) {
        this.myCompanyDetailInfo = comMesRes.data

        if (comMesRes.data.imgurl != '') {
          comMesRes.data.imgurl && (this.images = comMesRes.data.imgurl.split(','))
        }
      }
      let params = {
        company_id: comMesRes.data.id,
        status: '1'
      }
      const res = await reqHomeCompanyLists(params)
      if (res.code === 200) {
        this.loadType = false
        this.ownerJobList = res.data.items
        this.total = res.data.count || 0
      }
    },

    bigImage(img) {
      ImagePreview({
        images: img,
        closeable: true
      })
    },
    async getNotice() {
      const formData = {
        company_id: this.companyId,
        type: -1,
        key: ''
      }
      const res = await this.$api.company.reqGetComNotice(formData)
      for (let i = 0; i < res.data.items.length; i++) {
        this.noticeList.push(res.data.items[i].intro)
      }
    },
    //公告
    toNotice() {
      this.$router.push({
        path: `/myCompany/Notice`
      })
    },
    //滑动完最后一张的时候自动跳到公司介绍的页面
    onImageChange(index) {
      if (this.$refs.mySwipe.active == this.images.length) {
        if (
          Math.abs(this.$refs.mySwipe.deltaX) > Math.abs(this.$refs.mySwipe.deltaY) &&
          this.$refs.mySwipe.deltaX < 0
        ) {
          //从右侧向左滑动
          this.$router.push({
            path: `/myCompany/Introduce`
          })
        }
      }
    },
    onSearch() {
      this.searchParams.pageIndex = 1
      this._getJobList_company()
    },

    onClearVal(isQuery = true) {
      if (!isQuery) {
        return null
      }
      this.searchParams.keyword = ''
      this.searchParams.pageIndex = 1
      this._getJobList_company()
    },

    backMinePage() {
      localStorage.removeItem('tabItemIndex_myCompany')
      this.$router.push('/mine')
    },

    // 点击筛选
    clickFilter_myCompany() {
      let filterPopupRef_myCompany = this.$refs.comFilterPopupRef_myCompany
      filterPopupRef_myCompany.changeFilterPopupState()
    },

    // 筛选条
    getFilterBarVal_myCompany(needParamObj) {
      console.log('当前值---筛选条', needParamObj)
      Object.assign(this.searchParams, needParamObj)

      this.searchParams.pageIndex = 1
      this._getJobList_company()
    },

    // 侧边筛选栏
    toGetFilterPopUpVal_myCompany(val, val_2) {
      console.log('子--父', val)
      this.searchParams.classproperties = val.select_class_id // 班制：坐班、站班
      this.searchParams.jobattributes = val.select_position_attribute_id // 职位属性：两班倒、三班倒、、、
      this.searchParams.benefits = concatIds(val.select_welfare_list) // 福利列表
      this.searchParams.paymode = val.select_payWay_id // 算薪方式
      this.searchParams.payday = val.select_payMoneyDay_id // 发薪日
      this.searchParams.payMoneyDetailDate = val.select_payMoneyDay_detail // 发薪日详细日期
      this.searchParams.createTime = val.select_publish_date // 发布时间

      console.log('searchParams:', this.searchParams)

      this._updateFilterOperationObj(val_2)

      this.searchParams.pageIndex = 1
      this._getJobList_company()
    },

    // 获取我的公司职位列表分页
    async _getJobList_company() {
      const res = await this.$api.myCompany.getMyCompanyJobPage(this.searchParams)
      if (res.code === 200) {
        this.ownerJobList = res.data.items
        this.total = res.data.count
      }
    },

    toJobDetailPage(id) {
      console.log('首页封装组件---子到父', id)
      this.$router.push({
        path: `/jobDetail/${id}`
      })
    },
    // 公司链接toast
    showDig() {
      if (this.allUserInfo.id) {
        const {
          account,
          ids,
          company_id = '',
          p = 2,
          certification_state,
          g = 2,
          company_certification_state
        } = this.allUserInfo

        this.link =
          this.base_url +
          '?' +
          `rpId=${ids}&gId=${company_id}&p=${certification_state}&g=${company_certification_state}&st=V&account=${this.$Base64.encode(
            account
          )}`

        Dialog.confirm({
          title: '温馨提示',
          message: `将我的链接复制、粘贴到手机短信、微信朋友圈、QQ空间等各大社交软件，发送给好友注册下载，推广企业用户赚企业提成，推广个人用户赚代招费。我的链接为：${this.link}`,
          confirmButtonText: '复制链接',
          confirmButtonColor: '#1989FA',
          messageAlign: 'left'
        })
          .then(() => {
            // 点击确定
            this.$copyText(this.link).then(
              () => Toast('复制成功'),
              () => Toast('复制出错')
            )
          })
          .catch(() => {
            // on cancel
          })
      } else {
        let allCertificate = window.localStorage.getItem('allCertificate')
        // 没有登录凭证跳转登录页
        if (!allCertificate) {
          this.$store.dispatch('logOut')
          Dialog.confirm({
            message: '此功能需要注册登入才能使用，为您跳转到注册登入页面。'
          })
            .then(() => {
              this.$router.push({
                path: '/login'
              })
            })
            .catch(() => {
              // on cancel
            })
        }
      }
    },
    getReportNotice() {
      const {user_id} = this
      this.$api.company
        .getReportNotice({user_id})
        .then(res => {
          if (res.code === 200) {
            const {reportCount, suggestCount} = res.data

            this.reportCount = reportCount || 0
            this.suggestCount = suggestCount || 0
          } else {
            Toast(res.info || '接口错误')
          }
        })
        .catch(err => {
          // Toast(err || '系统错误')
        })
    },
    // 跳转举报投诉列表页
    toComplaintList(title, count) {
      const {user_id} = this
      const query = {title, user_id, from: 'company'}

      if (count > 0) {
        this.$router.push({
          path: '/complaintList',
          query
        })
      } else {
        Toast(`暂时没有收到${title}哦~`)
      }
    },

    handlePaginationChange_myCompany(pageIndex) {
      this.searchParams.pageIndex = pageIndex
      this._getJobList_company()
    },

    async toChangeJobStatus(obj) {
      // console.log('子---父', obj);
      const resp = await reqChangeJobStatus(obj)
      // console.log('响应值', resp);
      if (resp.code === 200) {
        const stateTextObj = {
          '-1': '默认',
          '0': '在招',
          '1': '停招'
        }
        Dialog.alert({
          message: `操作成功。已设置为：【${stateTextObj[obj.state]}】！！！`,
          messageAlign: 'left'
        }).then(() => {
          this._getJobList_company()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page_companyHome {
  min-height: 100vh;
  //公告
  .company-notice {
    height: 30px;
    width: 100%;
    background: white;
    font-weight: bold;

    .notice_bar {
      font-weight: 500;
    }

    // margin-top: 10px;
    .notice-wrap {
      width: 100%;
      height: 100%;
      display: flex;
      padding: 0 5px;
      align-items: center;
      box-sizing: border-box;

      .notice-left {
        border-right: 1px solid #a8a8a8;
        padding: 0 5px;
      }

      .notice-right {
        flex: 1;
        height: 100%;

        .van-notice-bar {
          height: 100%;
          padding: 0 2px;
          background: transparent;
          .notice-swipe {
            height: 40px;
            line-height: 40px;
            font-weight: 400;
          }
        }
      }
    }
  }
  .over_layer {
    margin-top: 46px;
    height: 100%;
    .layer {
      width: 46%;
      font-size: 14px;
      position: absolute;
      right: 0;
      z-index: 2;
    }
  }
  .van-image {
    height: 100%;
  }
  .my-swipe {
    width: 100%;
    height: 200px;
    overflow: hidden;
  }

  /deep/ .van-badge {
    right: 6px;
    top: 12px;
    min-width: 20px;
  }
}
</style>
